package com.cn.wanxi.publisher.service.impl;

import com.cn.wanxi.publisher.domain.entity.User;
import com.cn.wanxi.publisher.domain.model.ResultModel;
import com.cn.wanxi.publisher.mapper.UserMapper;
import com.cn.wanxi.publisher.service.IUserService;
import com.cn.wanxi.publisher.util.ParamUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @ClassName UserServiceImpl
 * @Description 用户服务层实现类
 * @Author JiJiang
 * @Date 2022/9/28 19:21
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements IUserService {


    //rabbitMQ的模板对象
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //redis的模板对象
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public ResultModel addUser(User user) {


        //注册的用户、用户名、密码有一个为空时，直接返回失败结果
        if (Objects.isNull(user)
                || Strings.isEmpty(user.getUsername())
                || Strings.isEmpty(user.getPassword())) {
            return ResultModel.getResult("<font color=\"red\">非法操作！</font>");
        }


        //1.根据用户名查询redis中是否有用户名
        //有则说明已经该用户名已被使用，没有则说明注册成功
        Object userInRedis = redisTemplate.opsForValue().get(ParamUtil.REDIS_REGISTER_USERNAME_PREFIX + user.getUsername());

        //redis中没有该用户名
        if (Objects.isNull(userInRedis)) {
            rabbitTemplate.convertAndSend(ParamUtil.EXCHANGE_NAME_USER, "wx.user.register", user);
            return ResultModel.getResult("注册成功！");
        }
        return ResultModel.getResult("注册失败！该用户名已存在");

    }


}
